<template>
  <el-alert
    v-if="show"
    class="fixed left-1/2 w-96 z-[100] top-[100px] transform -translate-x-1/2"
    :title="$t('appHeader.helpTip')"
    type="warning"
    center
  />
  <button type="button" class="header-button" @click="openHelpDialog">
    <span class="absolute -inset-1.5" />
    <span class="sr-only">{{ $t('appHeader.help') }}</span>
    <question-mark-circle-icon class="h-6 w-6" aria-hidden="true" />
  </button>
  <component
    ref="dialogRef"
    :is="dynamicComponent"
    @dectectChildLoad="dectectChildLoad"
    @resetChildLoadStatus="resetChildLoadStatus"
  />
</template>

<script setup lang="ts">
import { QuestionMarkCircleIcon } from '@heroicons/vue/24/outline';
import { useGlobalStore } from '@/store/global';

const globalStore = useGlobalStore();

defineProps<{ params: string }>();
const childLoadFinished = ref(false);
const $router = reactive(useRouter());
const dynamicComponent = shallowRef();
const show = ref(false);
const dialogRef = ref();

const dectectChildLoad = () => {
  childLoadFinished.value = true;
};
const resetChildLoadStatus = () => {
  childLoadFinished.value = false;
};
const transformString = globalStore.transformString;

const openHelpDialog = () => {
  const componentName = `${transformString($router.currentRoute.name as string)}Help`;
  dynamicComponent.value = defineAsyncComponent(
    () =>
      import(`@/components/HelpDocument/${componentName}.vue`).catch(() => {
        show.value = true;
        setTimeout(() => {
          show.value = false;
        }, 5000);
        dynamicComponent.value = null;
      }) as any,
  );
  // wait for child component OnMounted.
  const watchLoad = watch(childLoadFinished, () => {
    if (childLoadFinished.value === true) {
      dialogRef.value.dialogTableVisible = true;
      watchLoad();
    }
  });
};
</script>
